package com.jilian.powerstation.modul.fragment;

import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jilian.powerstation.MyApplication;
import com.jilian.powerstation.R;
import com.jilian.powerstation.base.BaseDto;
import com.jilian.powerstation.base.BaseFragment;
import com.jilian.powerstation.common.dto.BaseResultDto;
import com.jilian.powerstation.common.dto.PowerCardDto;
import com.jilian.powerstation.common.dto.PowerDto;
import com.jilian.powerstation.manege.Weather.WeaterManager;
import com.jilian.powerstation.manege.Weather.WeatherInfo;
import com.jilian.powerstation.modul.viewmodel.PowerViewModel;
import com.jilian.powerstation.utils.DateUtil;
import com.jilian.powerstation.utils.EmptyUtils;
import com.jilian.powerstation.utils.IconUtils;
import com.jilian.powerstation.utils.PinziDialogUtils;
import com.jilian.powerstation.utils.ProUtils;
import com.jilian.powerstation.utils.RxTimerUtil;
import com.jilian.powerstation.utils.ToastUitl;

import java.util.Date;

import interfaces.heweather.com.interfacesmodule.bean.Lang;
import interfaces.heweather.com.interfacesmodule.bean.Unit;
import interfaces.heweather.com.interfacesmodule.bean.search.Search;
import interfaces.heweather.com.interfacesmodule.bean.weather.now.Now;
import interfaces.heweather.com.interfacesmodule.view.HeWeather;

/**
 * Created by cxz on 2019/6/2
 * <p>
 * Discrebe: 电站名片
 */
public class SiteCardFragment extends BaseFragment implements BDLocationListener {
    private TextView tvSiteName;
    private TextView tvDeviceName;
    private TextView tvOne;
    private TextView tvPowerTotal;
    private TextView tvPowerVersion;
    private TextView tvOnlineTime;
    private TextView tvPowerIntroduction;
    private ImageView ivWether;
    private TextView tvGoodAir;
    private TextView tvAdress;
    private ImageView ivBanner;
    private ImageView ivVersion;
    private LinearLayout llVersion;

    private PowerDto powerDto;
    private PowerViewModel viewModel;
    private PowerCardDto data;

    @Override
    protected void loadData() {
    }

    public void initDataAtFirstVisibleToUser(boolean isVisibleToUser) {
        lang = Lang.ENGLISH;
        unit = Unit.METRIC;
        powerDto = (PowerDto) getActivity().getIntent().getSerializableExtra("data");

        if (powerDto != null) {
            tvSiteName.setText(powerDto.getProductName());
            Glide.with(getActivity()).
                    load(powerDto.getPhotopath())//电站卡片 LOGO 待定，先固定(你他妈吃屎去吧，改来改去，鸡巴)
                    .error(R.mipmap.img_site_card)
                    .placeholder(R.mipmap.img_site_card)
                    .into(ivBanner);//在RequestBuilder 中使用自定义的ImageViewTarge
            getPowerCard();
        }
        startLocationCilent();

        PowerDto mPowerDto = (PowerDto) getActivity().getIntent().getSerializableExtra("data");
        getWeater(mPowerDto.getLatitude(),mPowerDto.getLongitude());
    }

    @Override
    protected void createViewModel() {
        viewModel = ViewModelProviders.of(this).get(PowerViewModel.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_site_card;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        tvSiteName = (TextView) view.findViewById(R.id.tv_site_name);
        tvDeviceName = (TextView) view.findViewById(R.id.tv_device_name);
        tvOne = (TextView) view.findViewById(R.id.tv_one);
        tvPowerTotal = (TextView) view.findViewById(R.id.tv_power_total);
        tvPowerVersion = (TextView) view.findViewById(R.id.tv_power_version);
        tvOnlineTime = (TextView) view.findViewById(R.id.tv_online_time);
        tvPowerIntroduction = (TextView) view.findViewById(R.id.tv_power_introduction);
        ivWether = (ImageView) view.findViewById(R.id.iv_wether);
        tvGoodAir = (TextView) view.findViewById(R.id.tv_good_air);
        tvAdress = (TextView) view.findViewById(R.id.tv_adress);
        ivBanner = (ImageView) view.findViewById(R.id.iv_banner);
        ivVersion = (ImageView) view.findViewById(R.id.img_version);
        llVersion = view.findViewById(R.id.ll_version);
    }

    private String nowTmp;
    private String location;
    private String language;
    private ImageView ivBack;
    private String condCode;
    private Lang lang;
    private Unit unit;

    @Override
    protected void initData() {
    }


    /**
     * 退出登录对话框
     */
    private void showLogoutDialog(String strContent) {
        Dialog dialog = PinziDialogUtils.getDialogNotTouchOutside(getmActivity(), R.layout.dialog_confirm);
        TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tvContent = (TextView) dialog.findViewById(R.id.tv_content);
        TextView tvNo = (TextView) dialog.findViewById(R.id.tv_no);
        TextView tvOk = (TextView) dialog.findViewById(R.id.tv_ok);

        tvTitle.setText("Firmware Update Tips");
        tvContent.setText(strContent);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                getLoadingDialog().showDialog();
                RxTimerUtil.timer(500, new RxTimerUtil.IRxNext() {
                    @Override
                    public void doNext() {
                        updatePowerFirmwareInfo();
                    }
                });
            }
        });
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();


    }


    /**
     * 获取电站名片数据
     */
    private void getPowerCard() {
        showLoadingDialog();
        viewModel.getPowerCard(powerDto.getSn());
        viewModel.getPowerCardliveData().observe(this, new Observer<BaseDto<PowerCardDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<PowerCardDto> dtoBaseDto) {
                hideLoadingDialog();
                if (dtoBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(dtoBaseDto.getData())) {
                        initDataView(dtoBaseDto.getData());
                    }
                } else {
                    ToastUitl.showImageToastTips(dtoBaseDto.getMsg());
                }
            }
        });

    }

    /**
     * 展示卡片数据
     *
     * @param data
     */
    private void initDataView(PowerCardDto data) {
        this.data = data;
        tvOne.setText(ProUtils.getValueStr(data.getSpecification()));//电站规格
        tvPowerVersion.setText(data.getVersion());//版本
        tvOnlineTime.setText(DateUtil.dateToString(DateUtil.DEFAULT_DATE_FORMATTER, new Date(data.getTime())));
        tvPowerIntroduction.setText(ProUtils.getValueStr(data.getRemark()));//电站简介
        tvAdress.setText(data.getAddress());

        tvSiteName.setText(ProUtils.getValueStr(data.getPowerName()));
        tvDeviceName.setText(ProUtils.getValueStr(data.getDeviceName()));
        tvPowerTotal.setText(ProUtils.getValueOne(data.getQuantityCou(), 0.1F) + " kWh");

        if (data != null && data.isNewVersion()) {
            ivVersion.setVisibility(View.VISIBLE);
        } else {
            ivVersion.setVisibility(View.GONE);
        }
    }


    @Override
    protected void initListener() {
        ivVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data != null && data.isNewVersion()) {
                    showLogoutDialog("Firmware update description\n" + (data != null ? data.getVersionDescribed() : ""));
                }
            }
        });

    }

    /**
     * 更新固件
     */
    private void updatePowerFirmwareInfo() {
        showLoadingDialog();
        viewModel.updatePowerFirmwareInfo(powerDto.getSn());
        viewModel.getUpdateliveData().observe(this, new Observer<BaseDto<BaseResultDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<BaseResultDto> resultDtoBaseDto) {
                hideLoadingDialog();
                if (resultDtoBaseDto.isSuccess()) {
                    if ("1".equals(resultDtoBaseDto.getData().getResult())) {
                        getPowerCard();
                        ToastUitl.showImageToastTips("update success");
                    } else {
                        ToastUitl.showImageToastTips("update failuer");
                    }
                } else {
                    ToastUitl.showImageToastTips(resultDtoBaseDto.getMsg());
                }
            }
        });
    }

    /**
     * 开启定位
     */
    private void startLocationCilent() {
        // 申请权限
        MyApplication.getInstance().mLocationClient.start();
        MyApplication.getInstance().mLocationClient.registerLocationListener(this);
    }


    private double currentLat;//当前位置的维度
    private double currentLon;//当前位置的维度

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if (bdLocation != null) {
            currentLat = bdLocation.getLatitude();
            currentLon = bdLocation.getLongitude();

            MyApplication.getInstance().mLocationClient.stop();

        }
    }
    WeaterManager weaterManager = new WeaterManager();


    private void getWeater(double currentLat, double currentLon) {
        weaterManager.getWeather("https://api.openweathermap.org/data/2.5/weather", currentLat, currentLon, new WeaterManager.HttpCallBack<String>() {
            @Override
            public void onSuccess(String o) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(o)) {
                            WeatherInfo info = null;
                            try {
                                info  = new Gson().fromJson(o, WeatherInfo.class);
                            }catch (Exception e){
                                return;
                            }
                            int tem = (int) info.getMain().getTemp();
                            tvGoodAir.setText( tem+ "°C");
                            if (info.getWeather() != null && info.getWeather().size() > 0) {
                                WeatherInfo.WeatherBean weatherBean = info.getWeather().get(0);
                                Glide.with(getActivity()).
                                        load(String.format("https://openweathermap.org/img/w/%s.png", weatherBean.getIcon()))
                                        .into(ivWether);//
                            }


                        }
                    }
                });

            }

            @Override
            public void onError(Exception e) {
                Log.e("TAG_WEATHER","Exception------>"+new Gson().toJson(e));
            }
        });
    }

}
